package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import jsyf.com.constant.Const;
import jsyf.com.util.BaseUtils;
import jsyf.oa.dao.system.DepartDao;
import jsyf.oa.dao.system.RoleDao;
import jsyf.oa.entity.system.DepartEntity;
import jsyf.oa.facade.system.DepartFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class DepartService implements DepartFacade {

    //部门dao
    @Autowired
    private DepartDao departDao;
    @Autowired
    private RoleDao roleDao;


    /**
     * @param jsonData
     * @Description: 保存/修改部门  <br/>
     * @return: java.lang.String
     * @throw:
     * @author: 徐波
     * @createTime: 2017/11/27 0027 10:11
     * @Version: V1.0.0
     */
    @Override
    public String save(String  jsonData) {
        DepartEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), DepartEntity.class);
        Integer rows;
        if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
            rows = departDao.add(entity);
        } else {
            DepartEntity departEntity = departDao.getById(entity.getId());
            departEntity.setName(entity.getName());
            departEntity.setUpdateUserId(entity.getUpdateUserId());
            if(!StringUtils.isBlank(entity.getParentId())){
                departEntity.setParentId(entity.getParentId());
            }
            if(!StringUtils.isBlank(entity.getCompanyId())){
               departEntity.setCompanyId(entity.getCompanyId());
           }
            rows = departDao.update(departEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    /**
     * @param id
     * @Description: 逻辑删除部门  <br/>
     * @return: java.lang.String
     * @throw:
     * @author: 徐波
     * @createTime: 2017/11/27 0027 10:11
     * @Version: V1.0.0
     */
    @Override
    public String delById(String id) {
        Integer roleCount = roleDao.getPageCount(" AND DEPART_ID=? AND DEL_FLAG=0", new Object[]{id});
        if (roleCount > 0) {
            return BaseUtils.errorrRespond("删除失败，请先删除职位");
        }
        int flag = this.departDao.delById(id);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public Boolean sort(String departIds) {
        return  departDao.sort(departIds);
    }
}
